﻿//-----------------------------------------------------------------------
// <copyright file="TaskBase.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Kernel{    using System;
    using System.ComponentModel;

    /// <summary>
    /// Describes the basis structure of the services created for this worker.
    /// </summary>
    public abstract class TaskBase
    {
        /// <summary>
        /// Fired when the task is already completed
        /// </summary>
        public event EventHandler TaskCompleted;

        /// <summary>
        /// Fired when the task is already started
        /// </summary>
        public event EventHandler TaskStarted;

        /// <summary>
        /// Fired when the task is about to start, so it can be cancelled.
        /// </summary>
        public event CancelEventHandler TaskStarting;

        /// <summary>
        /// Fired when an error occurred within the task.
        /// </summary>
        public event EventHandler<TaskErrorEventArgs> TaskError;

        /// <summary>
        /// Gets a value indicating whether the task is still running and can't be launched.
        /// </summary>
        public bool IsRunning { get; private set; }

        /// <summary>
        /// Gets or sets the timeout within which the timeout should survive.
        /// </summary>
        public int Timeout { get; set; }

        /// <summary>
        /// Runs the execution pipeline for the performance of work by this task.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Design",
            "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Rethrowing the exception could critical services. We therefore publish the error through an event which can be listened by whoever implements task manager.")]
        public void Run()
        {
            // this will prevent the task from run twice before finishing the first invoke.
            if (!this.IsRunning)
            {
                try
                {
                    // double checked
                    if (this.IsRunning)
                    {
                        return;
                    }

                    // flags the task as running.
                    // this is the first thing to do and it will prevent
                    // the tasks manager from launching it twice.
                    this.IsRunning = true;

                    // we launch the event starging, so it can be interrupted by the service manager.
                    var args = new CancelEventArgs(false);
                    this.OnTaskStarting(args);
                    if (args.Cancel)
                    {
                        return;
                    }

                    // finallywe fire the event started.
                    this.OnTaskStarted(EventArgs.Empty);

                    // now, we will try to perform the work
                    // it's important to notice that, nothing is assync here.
                    // the invoker may be implemented with an assync invoker.
                    try
                    {
                        this.Perform();
                    }
                    catch (Exception ex)
                    {
                        // in case an unhalted exception is thrown, we notify the error event to the task
                        // this can be logged by the task manager
                        var argsForError = new TaskErrorEventArgs(
                            long.MinValue,
                            string.Empty,
                            ex);

                        this.OnTaskError(argsForError);
                    }

                    // here we launch the completed event
                    this.OnTaskCompleted(EventArgs.Empty);
                }
                finally
                {
                    // and finally, we clean up the running flag.
                    this.IsRunning = false;
                }
            }
        }
        
        /// <summary>
        /// Performs the tasks for which the class was designed.
        /// </summary>
        protected abstract void Perform();

        /// <summary>
        /// Fires the event TaskCompleted.
        /// </summary>
        /// <param name="e">The event args sent to this event method</param>
        protected virtual void OnTaskCompleted(EventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            if (this.TaskCompleted != null)
            {
                this.TaskCompleted(this, e);
            }
        }

        /// <summary>
        /// Fires the event TaskStarted.
        /// </summary>
        /// <param name="e">The event args sent to this event method</param>
        protected virtual void OnTaskStarted(EventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            if (this.TaskStarted != null)
            {
                this.TaskStarted(this, e);
            }
        }

        /// <summary>
        /// Fires the event TaskStarting.
        /// </summary>
        /// <param name="e">The event args sent to this event method</param>
        protected virtual void OnTaskStarting(CancelEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            
            if (this.TaskStarting != null)
            {
                this.TaskStarting(this, e);
            }

            if (e.Cancel)
            {
                return;
            }
        }

        /// <summary>
        /// Fires the event TaskError.
        /// </summary>
        /// <param name="e">The event args sent to this event method</param>
        protected virtual void OnTaskError(TaskErrorEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            
            if (this.TaskError != null)
            {
                this.TaskError(this, e);
            }
        }
    }
}


